package cn.donting.web.desktop.plugin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.TaskOutputsInternal;
import org.springframework.boot.gradle.tasks.bundling.BootJar;
import org.springframework.boot.loader.tools.Library;

import java.io.*;
import java.util.*;
import java.util.jar.JarFile;

/**
 * sys 打包插件
 */
public class SysJarTask extends DefaultTask {

    private List<File> libs;


    public void libs(List<File> libs) {
        this.libs = libs;
    }

    public void build() throws IOException {
        Project project = getProject();

        BootJar bootJar = (BootJar) project.getTasks().getByName("bootJar");

        TaskOutputsInternal outputs = bootJar.getOutputs();
        FileCollection files = outputs.getFiles();
        //booJar  输出的文件
        File booJarOutFile = (File) files.getFiles().toArray()[0];

        JarFile jarFile = new JarFile(booJarOutFile);
        String prefix = FileUtil.getPrefix(booJarOutFile);

        //重新打包输出文件
        File tragetFile = new File(booJarOutFile.getParentFile() + File.separator + prefix+"-wap.jar");

        AppJarWriter jarWriter = new AppJarWriter(tragetFile);
        //将 booJarOutFile class 写入 输出文件
        jarWriter.copyForBooJar(booJarOutFile);
        List<File> topLib = new ArrayList<>();

        //解压 booJarOutFile
        File unzip = ZipUtil.unzip(booJarOutFile);
        File libDir=new File(unzip+File.separator+"BOOT-INF"+File.separator+"lib");
        File[] libs = libDir.listFiles();
        //将 lib 写入 目标文件
        for (File lib:libs){
            if (lib.getName().contains("jakarta.servlet-api-") ||
                    lib.getName().contains("web-desktop-top-")||
                    lib.getName().contains("jakarta.websocket-api-")
            ) {
                topLib.add(lib);
                continue;
            }
            try {
                Library library = new Library(lib, null);
                //写入lib
                jarWriter.writeNestedLibrary("BOOT-INF/lib/", library);
            } catch (Exception e) {
                e.printStackTrace();
                jarWriter.close();
                return;
            }
        }
        //将 jakarta.servlet-api- web-desktop-top- 写入顶层包
        for (File file : topLib) {
            jarWriter.copyForBooJar(file);
        }
        jarWriter.writeManifest(jarFile.getManifest());
        jarWriter.close();
        FileUtil.del(unzip);
        System.out.println(tragetFile);


    }
}
